﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace TaxonomyReader
{
    public class SerializeDeserialize
    {
        public void Serialize(string fileName, object obj)
        {
            if (!Directory.Exists(TaxonomyLoader.SerializedFilesPath))
            {
                Directory.CreateDirectory(TaxonomyLoader.SerializedFilesPath);
            }

            Stream stream=null;
            try
            {
                stream = File.Open(TaxonomyLoader.SerializedFilesPath + fileName + ".bin", FileMode.Create);
                BinaryFormatter bformatter = new BinaryFormatter();
                bformatter.Serialize(stream, obj);
                stream.Close();
            }
            catch
            {
                stream.Close();
            }
        }

        public object Deserialize(string fileName)
        {
            if (!Directory.Exists(TaxonomyLoader.SerializedFilesPath))
            {
                Directory.CreateDirectory(TaxonomyLoader.SerializedFilesPath);
            }

            if (!File.Exists(TaxonomyLoader.SerializedFilesPath + fileName + ".bin"))
                return null;

            object obj = null;

            Stream stream = null;
            try
            {
                //Open the file written above and read values from it.
                stream = File.Open(TaxonomyLoader.SerializedFilesPath + fileName + ".bin", FileMode.Open);
                BinaryFormatter bformatter = new BinaryFormatter();

                obj = bformatter.Deserialize(stream);
                stream.Close();
            }
            catch
            {
                stream.Close();
            }
            return obj;
        }
    }
}
